<template>
    <div class="file-upload">
        <h1>文件上传与下载</h1>
        
        <!-- 文件上传部分 -->
        <div>
            <h2>上传文件</h2>
            <input type="file" @change="onFileChange" />
            <button @click="handleUpload" :disabled="!selectedFile">上传文件</button>
            <p v-if="message">{{ message }}</p>
        </div>
        
        <!-- 文件下载部分 -->
        <div>
            <h2>下载文件</h2>
            <input type="text" v-model="filename" placeholder="输入文件在服务器的地址" />
            <input type="text" v-model="newFileName" placeholder="输入新文件名" />
            <button @click="handleDownload" :disabled="!filename">下载文件</button>
            <p v-if="downloadMessage">{{ downloadMessage }}</p>
        </div>
        
        <div>
            <h2>删除文件</h2>
            <input type="text" v-model="deleteFileName" placeholder="输入文件在服务器的地址" />
            <button @click="handleDelete" :disabled="!deleteFileName">删除服务器文件</button>
            <p v-if="deleteMessage">{{ deleteMessage }}</p>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';


        // 上传功能相关
        const selectedFile = ref(null);
        const message = ref('');
        
        // 下载功能相关
        const filename = ref('');
        const newFileName = ref('');
        const downloadMessage = ref('');
        
        const deleteFileName = ref('');
        const deleteMessage = ref('');
        
        // 删除文件逻辑 post请求删除文件
        const handleDelete = async () => {
            if (!deleteFileName.value) {
                deleteMessage.value = '请输入文件名!';
                return;
            }
            
            try {
                // const response = await axios.post(
                //     '/api/files/delete',
                //     {
                //         fileName: deleteFileName.value,
                //     }
                // );
                
                //使用post请求发送一个参数 就用 URLSearchParams  多个参数就用对象
                const response = await axios.post(
                    '/api/files/delete',
                    new URLSearchParams({ fileName: deleteFileName.value }).toString(),
                    {
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                    }
                );
                deleteMessage.value = `文件删除成功: ${response.data}`;
                deleteFileName.value = '';
            } catch (error) {
                console.error(error);
                deleteMessage.value = '文件删除失败，请重试！';
            }
        };
        
        // 文件选择变化
        const onFileChange = (event) => {
            selectedFile.value = event.target.files[0];
        };
        
        // 文件上传逻辑
        const handleUpload = async () => {
            if (!selectedFile.value) {
                message.value = '请先选择一个文件!';
                return;
            }
            
            const formData = new FormData();
            formData.append('file', selectedFile.value);
            
            try {
                const response = await axios.post('/api/files/upload', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                });
                message.value = `文件上传成功: ${response.data}`;
                selectedFile.value = null;
            } catch (error) {
                console.error(error);
                message.value = '文件上传失败，请重试！';
            }
        };
        
        // 文件下载逻辑
        const handleDownload = async () => {
            if (!filename.value) {
                downloadMessage.value = '请输入文件名!';
                return;
            }
            
            //文件名需要带上后缀
            try {
                //方法1  手动处理下载流程
                const response = await axios.get(`/api/files/download/?fileName=`+filename.value, {
                    responseType: 'blob', // 指定响应类型为二进制数据
                });
                // 创建下载链接
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                // //设置直接下载 并且指定文件名
                link.setAttribute('download', newFileName.value); // 设置下载的文件名
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                
                //方法2 自动处理下载流程 需要后端设置请求头 为 .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "newFile.doc" + "\"")
                // const link = document.createElement('a');
                // link.href = `http://localhost:8080/files/download/?filename=`+filename.value;
                // link.click();
                
                downloadMessage.value = '文件下载成功！';
            } catch (error) {
                console.error(error);
                downloadMessage.value = '文件下载失败，请检查文件名！';
            }
        };

</script>

<style>
.file-upload {
    max-width: 400px;
    margin: 50px auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
}
input[type="file"],
input[type="text"] {
    display: block;
    margin-bottom: 10px;
    width: 100%;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 5px;
}
button {
    background-color: #007bff;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    margin-bottom: 10px;
}
button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}
p {
    margin-top: 10px;
    color: green;
}
</style>
